package com.rpc.server.framework;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * com.rpc.server
 *
 * @author humdeef
 * @since 2019-07-17
 */
public class RpcServer {
  private ThreadPoolExecutor executor =
      new ThreadPoolExecutor(8, 30, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));
  private Map<String, Object> serviceList = new HashMap<>();

  public synchronized void publish(Class<?> clazz, Object object) {
    serviceList.put(clazz.getName(), object);
  }

  public void start(Integer port) {
    System.out.println("服务开始启动......");
    try {
      ServerSocket serverSocket = new ServerSocket();
      serverSocket.bind(new InetSocketAddress(port));
      while (true) {
        executor.execute(new SocketTask(serverSocket.accept(), serviceList));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
